/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.patrolRouteRecord.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.business.patrolRouteRecord.PatrolRouteRecordRestApi;
import org.opsli.api.wrapper.business.patrolRouteRecord.PatrolRouteRecordModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.common.utils.CheckStrength;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.CoordinatesConvertUtil;
import org.opsli.modulars.business.app.web.MapCordinatesVo;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.routeStation.entity.RouteStation;
import org.opsli.modulars.business.routeStation.service.impl.RouteStationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.opsli.modulars.business.patrolRouteRecord.entity.PatrolRouteRecord;
import org.opsli.modulars.business.patrolRouteRecord.service.IPatrolRouteRecordService;

/**
 * 巡线记录 Controller
 *
 * @author zk
 * @date 2021-09-16 15:12:07
 */
@Api(tags = PatrolRouteRecordRestApi.TITLE)
@Slf4j
@ApiRestController("/business/patrolRouteRecord")
public class PatrolRouteRecordRestController extends BaseRestController<PatrolRouteRecord, PatrolRouteRecordModel, IPatrolRouteRecordService>
        implements PatrolRouteRecordRestApi {


    /**
     * 巡线记录 查一条
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "获得单条巡线记录", notes = "获得单条巡线记录 - ID")
    @RequiresPermissions("patrolrouterecord_select")
    @Override
    public ResultVo<PatrolRouteRecordModel> get(PatrolRouteRecordModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    /**
     * 巡线记录 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultVo
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @RequiresPermissions("patrolrouterecord_select")
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {
        Map<String, String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        queryMap.put("devid_EQ", new String[]{UserUtil.getSysUser().getCompanyId()});
        QueryBuilder<PatrolRouteRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<PatrolRouteRecord, PatrolRouteRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }


    @Override
    public ResultVo<List<Map>> findLast(String userId) {
        List<Map> list = new ArrayList();
        PatrolRouteRecord record = IService.findLast(userId);
        if (record != null && ZkUtils.isNotBlank(record.getTrail())) {
            list = JSON.parseArray(record.getTrail(), Map.class);
            for (Map map : list) {
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                    cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());
                    Object o = map.get("tm");
                    if (o == null) {
                        map.put("tm", "");
                    }
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                }

            }
        }
        return ResultVo.success(list);
    }

    @Override
    public ResultVo<List<Map>> findLastHome(String userId) {
        List<Map> list = new ArrayList();
        PatrolRouteRecord record = IService.findLastHome(userId);

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = ft.parse(record.getLastTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat ft1 = new SimpleDateFormat("yyyy-MM-dd");
        String time = ft1.format(date);


        if (record != null && ZkUtils.isNotBlank(record.getTrail())) {
            list = JSON.parseArray(record.getTrail(), Map.class);
            for (Map map : list) {
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                    cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());

                    Object o = map.get("tm");

                    if (o == null) {
                        map.put("tm", "");
                    }else {
                        String timeDate=o.toString();
                        String lo=time;
                        lo+=" ";
                        lo+=timeDate;
                        map.put("tm", lo);
                    }
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                }

            }
        }
        return ResultVo.success(list);
    }

    @Override
    public ResultVo<Map> findLastGj(String userId) {
        PatrolRouteRecord record = IService.findLast(userId);
        Map datamap = new HashMap();
        List<Map> list1 = new ArrayList();
        List<Map> list2 = new ArrayList();
        if (record.getTrail() != null && !record.getTrail().equals("")) {
            list1 = JSON.parseArray(record.getTrail(), Map.class);
            for (Map map : list1) {
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                    cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());
                    Object o = map.get("tm");
                    if (o == null) {
                        map.put("tm", "");
                    }
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                }

            }
        }
        List<RouteStation> stations = IService.findList("1460527119716057089");
        if (stations != null && stations.size() > 0) {
            for (RouteStation station : stations) {
                Map map = new HashMap();
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(station.getLongitude()));
                    cordinatesVo.setLat(new BigDecimal(station.getDimension()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());
                    map.put("lo", station.getLocation());
                    list2.add(map);
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(station));
                }

            }
        }
        datamap.put("trail", list1);
        datamap.put("route", list2);
        return ResultVo.success(datamap);
    }

    @Autowired
    RouteStationServiceImpl rs;

    @Override
    public ResultVo<Map> findTrail(String id) {
        String devid = UserUtil.getSysUser().getCompanyId();
        PatrolRouteRecordModel record = IService.get(id);
        Map datamap = new HashMap();
        List<Map> list1 = new ArrayList();
        List<Map> list2 = new ArrayList();
        if (record.getTrail() != null && !record.getTrail().equals("")) {
            list1 = JSON.parseArray(record.getTrail(), Map.class);
            for (Map map : list1) {
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                    cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("lt", cordinatesVo.getLon());
                    map.put("ln", cordinatesVo.getLat());
                    Object o = map.get("tm");
                    if (o == null) {
                        map.put("tm", "");
                    }
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                }

            }
        }
        List<RouteStation> stations = IService.findList(record.getRouteId());
        if (stations != null && stations.size() > 0) {
            for (RouteStation station : stations) {
                Map map = new HashMap();
                try {
                    MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                    cordinatesVo.setLon(new BigDecimal(station.getLongitude()));
                    cordinatesVo.setLat(new BigDecimal(station.getDimension()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    if (devid.equals("41006")){
                        map.put("lt", station.getLongitude());
                        map.put("ln", station.getDimension());
                    } else {
                        map.put("lt", cordinatesVo.getLon());
                        map.put("ln", cordinatesVo.getLat());
                    }
                    map.put("lo", station.getLocation());
                    list2.add(map);
                } catch (Exception e) {
                    System.out.println("转换坐标错误=" + JSON.toJSONString(station));
                }
            }
        }
        List list = new ArrayList();
        if (devid.equals("41006")) {
            Integer joint= 1;
            Map map = new HashMap();
            map.put("devid", devid);
            list.add(map);
            List l2 = new ArrayList();
            List<RouteStation> l = rs.findAnZeList(record.getRouteId());
            for (int i = 0; i < l.size(); i++) {
                Map m = new HashMap();
                RouteStation r = l.get(i);
                String longitude = r.getLongitude();
                String dimension = r.getDimension();
                m.put("lt", longitude);
                m.put("ln", dimension);
                l2.add(m);
                if (longitude.equals("0") && dimension.equals("0")) {
                    joint= 2;
                    List l3 = new ArrayList();
                    for (int a = 0; a < l2.size() - 1; a++) {
                        l3.add(l2.get(a));
                    }
                    list.add(l3);
                    l2.clear();
                }
            }
            map.put("joint", joint);//是否是拼接 1 整段 2 拼接
        }
        datamap.put("localroute", list);
        datamap.put("trail", list1);
        datamap.put("route", list2);
        return ResultVo.success(datamap);

    }

    /**
     * 巡线记录 新增
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "新增巡线记录数据", notes = "新增巡线记录数据")
    @RequiresPermissions("patrolrouterecord_insert")
    @EnableLog
    @Override
    public ResultVo<?> insert(PatrolRouteRecordModel model) {
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增巡线记录成功");
    }

    /**
     * 巡线记录 修改
     *
     * @param model 模型
     * @return ResultVo
     */
    @ApiOperation(value = "修改巡线记录数据", notes = "修改巡线记录数据")
    @RequiresPermissions("patrolrouterecord_update")
    @EnableLog
    @Override
    public ResultVo<?> update(PatrolRouteRecordModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改巡线记录成功");
    }


    /**
     * 巡线记录 删除
     *
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除巡线记录数据", notes = "删除巡线记录数据")
    @RequiresPermissions("patrolrouterecord_update")
    @EnableLog
    @Override
    public ResultVo<?> del(String id) {
        IService.delete(id);
        return ResultVo.success("删除巡线记录成功");
    }

    /**
     * 巡线记录 批量删除
     *
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除巡线记录数据", notes = "批量删除巡线记录数据")
    @RequiresPermissions("patrolrouterecord_update")
    @EnableLog
    @Override
    public ResultVo<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除巡线记录成功");
    }


    /**
     * 巡线记录 Excel 导出
     * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
     * <p>
     * 导出时，Token认证和方法权限认证 全部都由自定义完成
     * 因为在 导出不成功时，需要推送错误信息，
     * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
     * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
     * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
     * response 推送 javascript代码 alert 提示报错信息
     *
     * @param request  request
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @RequiresPermissionsCus("patrolrouterecord_export")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        QueryBuilder<PatrolRouteRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        super.excelExport(PatrolRouteRecordRestApi.SUB_TITLE, queryBuilder.build(), response, method);
    }

    /**
     * 巡线记录 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     *
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("patrolrouterecord_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
     * 巡线记录 Excel 下载导入模版
     * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
     *
     * @param response response
     */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("patrolrouterecord_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(PatrolRouteRecordRestApi.SUB_TITLE, response, method);
    }

}
